import {isBlank} from "@test/util/ValidateUtil";
import {LoginException, ParamException} from "@test/common/HandleException";
import Sequelize from "@test/database";
import jwt from 'jsonwebtoken'
import config from '@test/config'
import blacklist from 'blacklist'
import {checkPassword} from "@test/util/PasswordUtil";


const userModel = Sequelize.model('user')

class UserService {
    static async login({username, password}) {
        if (isBlank(username)) {
            throw new ParamException('用户名不能为空')
        }
        if (isBlank(password)) {
            throw new ParamException('密码不能为空')
        }

        let user = await userModel.findOne({
            where: {
                phone: username
            }
        })

        if (!user) {
            throw new LoginException('账号或密码错误')
        }

        console.log(username, password)

        user = user.dataValues
        let check = await checkPassword(password, user.password)
        if (!check) {
            throw new LoginException('账号或密码验证失败')
        }


        /**
         * 从结果中把 password 排除掉，例如：
         * var someInput = { a: 1, b: 2, c: 3 }
         * blacklist(someInput, 'b', 'c')
         * output => { a: 1 }
         */
        let payload = blacklist(user, 'password')

        // payload could be an object literal,buffer or string representing valid JSON
        return jwt.sign(payload, config.jwt.secret, {
            expiresIn: config.jwt.expiresIn
        })
    }

    static async findById(id) {
        return userModel.findOne({where: {id: id} });
    }
}

export default UserService
